package com.java1412.controller.api;

import com.java1412.utils.ConstantUtil;
import com.java1412.utils.GenerateCodeUtil;
import com.java1412.utils.ResponseUtil;
import com.java1412.utils.SmsUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 生成验证码控制器
 *
 * @author java1412
 * @since 2023-06-21 13:34:14
 */
@RestController
@RequestMapping("/api/vc")
public class VerifyCodeController {
    @Resource
    private GenerateCodeUtil generateCodeUtil;

    @Resource
    private SmsUtil smsUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/sendVc")
    public Object sendVc(String phone) {
        ResponseUtil r = null;
        try {
            // 生成验证码
            String verifyCode = generateCodeUtil.generateVerifyCode();
            System.out.println("验证码:" + verifyCode);
            // 发送验证码到指定的手机号,将来项目上线下面的代码要放开
            // smsUtil.sendVerifyCode(phone, verifyCode);
            // 向redis存储uuid 手机号 验证码
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 手机号-验证码
            // shfidhfdghidfghidghdifhgidf:18291986656-1234
            String value = phone + "-" + verifyCode;
            stringRedisTemplate.opsForValue().set(uuid, value, ConstantUtil.VERIFY_CODE_TIMEOUT, TimeUnit.SECONDS);
            // 发送验证码成功
            // 向页面返回状态
            Map<String, Object> map = new HashMap<>();
            map.put("uuid", uuid);
            r = ResponseUtil.ok("发送验证码成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            // 向页面返回状态
            r = ResponseUtil.fail("发送验证码失败");
        }
        return r;
    }
}
